package org.example.Servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;

@MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 1,  // 1 MB
        maxFileSize = 1024 * 1024 * 10,       // 10 MB
        maxRequestSize = 1024 * 1024 * 50     // 50 MB
)
@WebServlet("/upload")
public class ImageUploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 指定上传路径
        String uploadPath = "D:\\oo\\web\\images";

        // 确保路径存在，如果不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 获取上传的文件部分
        Part filePart = request.getPart("image");
        String fileName = getFileName(filePart);  // 获取文件名

        // 获取是否要添加新文件的标志
        boolean addNewFile = Boolean.parseBoolean(request.getParameter("addNewFile"));

        // 如果文件名不为空，进行文件上传
        if (fileName != null && !fileName.isEmpty()) {
            fileName = getUniqueFileName(uploadPath, fileName, addNewFile);  // 获取唯一的文件名
            try (InputStream fileContent = filePart.getInputStream()) {
                Path filePath = Paths.get(uploadPath, fileName);
                Files.copy(fileContent, filePath);  // 复制文件内容到指定路径
                // 返回 JSON 格式的响应
                response.setContentType("application/json");
                response.getWriter().write("{\"fileName\": \"" + fileName + "\"}");
            } catch (IOException e) {
                e.printStackTrace();
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().println("上传失败: " + e.getMessage());
            }
        } else {
            // 如果未选择文件，返回错误响应
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().println("上传失败: 未选择文件");
        }
    }

    // 获取上传文件的文件名
    private String getFileName(Part part) {
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }

    // 获取唯一的文件名，如果不添加新文件，则覆盖同名文件
    private String getUniqueFileName(String uploadPath, String fileName, boolean addNewFile) {
        File file = new File(uploadPath, fileName);
        if (!addNewFile && file.exists()) {
            return fileName;
        }

        int count = 1;
        String baseName = fileName.substring(0, fileName.lastIndexOf('.'));
        String extension = fileName.substring(fileName.lastIndexOf('.'));
        while (file.exists()) {
            fileName = baseName + "_" + count + extension;
            file = new File(uploadPath, fileName);
            count++;
        }
        return fileName;
    }
}
